package com.ainge.easystudy.thread;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Exchanger;

/**
 * @author: Ainge
 * @Time: 2021/8/30 01:23
 */
public class ExchangeTest {


    public static void main(String[] args) {
        List<String> buffer1 = new ArrayList<String>();
        List<String> buffer2 = new ArrayList<String>();
        // 公共
        Exchanger<List<String>> exchanger = new Exchanger<>();

        Thread producerThread = new Thread(new Producer(buffer1,exchanger));
        Thread consumerThread = new Thread(new Consumer(buffer2,exchanger));

        producerThread.start();
        consumerThread.start();


    }

    static class Producer implements Runnable {
        // 生产者数据
        private List<String> buff;
        // 生产者与消费者之间的交换管道
        private Exchanger<List<String>> exchanger;

        Producer(List<String> buff,Exchanger<List<String>> exchanger){
            this.buff = buff;
            this.exchanger = exchanger;
        }

        List<String> produce(){
            System.out.println("生产者装入");
            for(int j = 1 ; j <= 3 ; j++){
                buff.add("buffer：" + j );
            }
            return buff;
        }

        @Override
        public void run() {
            for (int i = 0; i < 5; i++) {
                List<String> produce = produce();
                System.out.println("生产者第"+i+"次装满，等待与消费者交换");
                try {
                    exchanger.exchange(produce);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        }
    }

    static class  Consumer implements Runnable {

        // 数据
        private List<String> buff;
        // 生产者与消费者之间的交换管道
        private Exchanger<List<String>> exchanger;

        Consumer(List<String> buff,Exchanger<List<String>> exchanger){
            this.buff = buff;
            this.exchanger = exchanger;
        }

        @Override
        public void run() {
            for (int i = 0; i < 5; i++) {
                //调用exchange()与消费者进行数据交换
                try{
                    System.out.println("消费者"+i+"次消费");
                    buff = exchanger.exchange(buff);
                    consume(buff);
                }catch (Exception e){

                }
            }
        }

        private void consume(List<String> buff) {
            for (int i = 0; i < 3; i++) {
                System.out.println("消费数据：" + buff.get(0));
                buff.remove(0);
            }
        }
    }

}
